<?php
/**
 * --------------------------------------------------------------
 * 后台基础控制器
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\common\controller;

use app\admin\model\Admin as AdminModel;
use app\admin\model\AuthRule as AuthRuleModel;

class AdminBase extends Base
{
    /**
     * 初始化
     */
    protected function initialize()
    {
        parent::initialize();

        $allowUrl = [
            'admin/index/login',
            'admin/index/logout'
        ];
        $rule = strtolower($this->request->module() . '/' . \think\Loader::parseName($this->request->controller()) . '/' . $this->request->action());
        if (in_array($rule, $allowUrl)) {
            return true;
        } else {
            if (defined('AID')) return;
            define('AID', (int) AdminModel::isLogin());
            if (false === $this->competence()) {
                $this->redirect('admin/login/index');
            } else {
                if (!(AID == 1)) {
                    if (!check_rule($rule, [1, 2, 3])) {
                        $this->error('未授权访问');
                    }
                }
            }
            $sidebar = AuthRuleModel::getSidebar();
            $this->assign('_sidebar', $sidebar);
            $this->assign('_location', AuthRuleModel::getLocation('', true));
        }
    }

    /**
     * 验证登录
     * @return array
     */
    private function competence()
    {
        $aid = (int) AdminModel::isLogin();
        if (empty($aid)) return false;

        $ainfo = AdminModel::getUserInfo($aid);
        if (empty($ainfo)) {
            AdminModel::logout();
            return false;
        }

        return $ainfo;
    }

    /**
     * 简单的搜索筛选条件
     */
    public function getSimpleSearchMap($map = [])
    {
        $keyword      = input('param.keyword/s', '');
		$search_field = input('param.search_field/s', '');

        //$map = empty($map) ? ['status' => 1] : $map;

        if ($search_field != '' && $keyword != '') {
            $map[] = [$search_field, 'like', "%$keyword%"];
        }

        return ['where' => $map, 'conditions' => ['keyword' => $keyword, 'search_field' => $search_field]];
    }
}